let utils = require('../../utils/utils.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        openBluetoothAdapter: false,
        available: false,
        discovering: false,
        connectingDeviceId: '',
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let userInfo = wx.getStorageSync("userInfo");
        if (userInfo) {
            this.setData({
                userInfo: userInfo
            })
        } else {
            wx.navigateTo({
                url: '/pages/login/login',
            })
        }
    },

    // 初始化蓝牙
    openEvent() {
        wx.getLocation({
            type: 'gcj02', //返回可以用于wx.openLocation的经纬度
            success: function (res) {
                // let latitude = res.latitude //维度
                // let longitude = res.longitude //经度
                console.log(res);
            }
        });
        this.openBluetooth();
    },
    //step1. 初始化蓝牙模块
    openBluetooth() {
        let _this = this;
        wx.openBluetoothAdapter({
            success(e) {
                if (e.errMsg == 'openBluetoothAdapter:ok') {
                    _this.setData({
                        openBluetoothAdapter: true
                    });
                    _this.getBluetoothState();
                }
            },
            fail() {
                wx.showModal({
                    title: '温馨提示',
                    content: '请检查手机蓝牙是否开启',
                    showCancel: false
                });
                _this.setData({
                    openBluetoothAdapter: false
                });
            },
        });
        //搜索蓝牙
        _this.linkXinaiBle();
    },

    //连接蓝牙
    linkXinaiBle() {
        let _this = this;
        if (_this.data.discovering) {
            utils.toast('正在搜索蓝牙...');
            return;
        }
        // 停止搜寻附近的蓝牙外围设备
        _this.stopDiscovery();

        // 获取本机蓝牙适配器状态
        _this.getBluetoothState();

        // 监听蓝牙适配器状态变化事件
        _this.onBluetoothStateChange();

        //s2. 开始搜寻附近的蓝牙外围设备
        _this.startDiscovery();

        //s3. 监听寻找到新设备，搜索到则跳转设备列表中
        _this.onFoundBluetooth();
    },

    // 停止搜寻附近的蓝牙外围设备
    stopDiscovery() {
        let _this = this;
        wx.stopBluetoothDevicesDiscovery({
            success(res) {
                console.log('停止搜寻附近的蓝牙外围设备');
                console.log(res);
                _this.setData({
                    discovering: false
                });
            },
            fail() {
                utils.toast('停止搜索失败');
            },
        });
    },
    // 获取本机蓝牙适配器状态
    getBluetoothState() {
        let _this = this;
        wx.getBluetoothAdapterState({
            success(e) {
                console.log("getBluetoothAdapterState本机蓝牙适配器状态: ", e);
                _this.setData({
                    available: e.available,
                    discovering: e.discovering,
                });
                return true;
            },
            fail() {
                _this.setData({
                    available: false,
                    discovering: false,
                });
                return false;
            }
        });
    },
    // 监听蓝牙适配器状态变化事件
    onBluetoothStateChange() {
        let _this = this;
        wx.onBluetoothAdapterStateChange(function (res) {
            console.log('监听蓝牙适配器状态变化:', res);
            _this.setData({
                available: res.available,
                discovering: res.discovering,
            });
        });
    },

    //step2. 开始搜寻附近的蓝牙外围设备
    startDiscovery() {
        let _this = this;
        wx.startBluetoothDevicesDiscovery({
            success(res) {
                console.log("开始搜寻附近的蓝牙外围设备：", res);
            },
            fail() {
                utils.toast('搜索失败');
            }
        })
    },

    //step3. 监听发现附近的蓝牙设备
    onFoundBluetooth() {
        let _this = this;
        wx.onBluetoothDeviceFound(function (res) {
            // 兼容安卓及iOS设备
            let new_devices;
            if (res.deviceId) {
                new_devices = res;
            } else if (res.devices) {
                new_devices = res.devices[0];
            } else if (res[0]) {
                new_devices = res[0];
            }
            console.log("发现的蓝牙设备", new_devices);
            //在这里判断有没有XIN-AI蓝牙，如果搜索到则停止
            if (new_devices.name && new_devices.name == 'XIN-AI') {
                console.log("找到XIN-AI停止搜索")
                _this.stopDiscovery();
                _this.data.discovering = true;
                _this.data.connectingDeviceId = new_devices.deviceId;
                //找到设备跳转到设备列表
                wx.navigateTo({
                    url: '/pages/device/list/list?connectingDeviceId=' + _this.data.connectingDeviceId,
                });
            }
        });
    },

}); //Page